﻿import flash.external.ExternalInterface;
import org.swxformat.SWX;

/**
* SWX JavaScript bridge class.
*/
class JsSWX {
	
	private var _swx:SWX;
	private var LOG:LocalConnection;
	
	private function log(msg:String) : Void {
		if(LOG) LOG.send("_swxDebugger", "debug", [msg]);
	}
	
	public function JsSWX() {
		if(_root.debug) {
			LOG = new LocalConnection();
			LOG.connect("_swxDebugger");
		}
		log("Instanciate SWX");
		_swx = new SWX();
		declareJavaScriptMethods();
	}
	
	private function declareJavaScriptMethods() {
		log("ExternalInterface is available ? " + ExternalInterface.available);
		if(ExternalInterface.available) {
			ExternalInterface.addCallback("call", this, call); 
			log("Declare js method : call");
			ExternalInterface.addCallback("setGateway", this, setGateway); 
			log("Declare js method : setGateway");
			ExternalInterface.addCallback("setDebug", this, setDebug); 
			log("Declare js method : setDebug");
			ExternalInterface.addCallback("setEncoding", this, setEncoding); 
			log("Declare js method : setEncoding");
		}
	}
	
	public function call(p:Object) : Void {
		prepareResultHandlerMapping(p);
		_swx.call(p);
	}
	
	private function prepareResultHandlerMapping(p:Object) : Void {
		if(p && p.result && p.result != "") {
			var resultMappingToken:String = p.result;
			p.result = [this, function(event:Object):Void {
				// FIXME could not send event object.
				ExternalInterface.call("JsSWX.resultHandler", resultMappingToken, event.result);
			}];
		}
	}
	
	public function setGateway(gateway:String) : Void {
		_swx.gateway = gateway;
	}
	
	public function setDebug(debug:Boolean) : Void {
		_swx.debug = debug;
	}
	
	public function setEncoding(encoding:String) : Void {
		_swx.encoding = encoding;
	}
}